package com.example.codefilter.project.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.example.codefilter.common.core.AjaxResult;
import com.example.codefilter.common.exception.ServiceException;
import com.example.codefilter.common.util.SecurityUtils;
import com.example.codefilter.framework.security.model.LoginUser;
import com.example.codefilter.project.sys.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * 登录控制器
 *
 * @author LiJunYi
 * @date 2022/07/26
 */
@Controller
public class LoginController
{
    /**
     * 身份验证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 登录页面
     *
     * @return {@link String}
     */
    @GetMapping("login")
    public String login() {
        return "login";
    }

    /**
     * 登录方法
     *
     * @param user 用户
     * @return {@link AjaxResult}
     */
    @PostMapping("userLogin")
    @ResponseBody
    public AjaxResult login(SysUser user)
    {
        if (StrUtil.isEmpty(user.getUsername()) || StrUtil.isEmpty(user.getPassword()))
        {
            return AjaxResult.error("用户名或密码未输入!");
        }
        // 用户验证
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));
        }catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                throw new ServiceException("密码错误");
            }
            else
            {
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return AjaxResult.success();
    }

    /**
     * 首页
     *
     * @return {@link String}
     */
    @GetMapping("index")
    public ModelAndView indexPage(ModelMap map)
    {
        map.put("username", SecurityUtils.getUsername());
        map.put("permissions",SecurityUtils.getLoginUser().getPermissions());
        return new ModelAndView("index", map);
    }

    /**
     * 无权限页面
     *
     * @return {@link String}
     */
    @PostMapping("noPermission")
    public String noPermissionHtml()
    {
        return "noPermission";
    }
}
